import { createRouter, createWebHashHistory } from 'vue-router'
import { useTokenStore } from '@iframe/tools/store/modules/token'
import { usePermissionStore } from '@iframe/tools/store/modules/permission'
import { generateRoutes, pushRoute } from './generateRoutes'
import { notice } from '@iframe/tools/components/index.js'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { SUCCESS_CODE } from '@iframe/tools/axios/axios.js'

const tokenStore = useTokenStore()
const permissionStore = usePermissionStore()
//白名单
const HOME_ROUTE_NAME = '首页'
const whiteRoute = ['/login', '/404', '/']

const routes = [
    {
        path: '',
        name: '空白页',
        redirect: '/login'
    },
    {
        path: import.meta.env.IFRAME_HOME_URL,
        name: '首页',
        component: () => import('/@/layouts/index.vue'),
        children: [
            {
                path: '',
                name: '欢迎页',
                component: () => import('/@/views/Home/index.vue')
            }
        ]
    },
    {
        path: '/login',
        name: '登录',
        component: () => import('/@/views/Login/index.vue')
    },
    {
        path: '/404',
        name: '错误页面',
        component: () => import('/@/views/Error/index.vue')
    },
    {
        path: '/:path(.*)*',
        name: '其他页面',
        component: () => import('/@/views/Login/index.vue')
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})
/**
 * 路由拦截器
 */
router.beforeEach((to, from, next) => {
    NProgress.start()
    if (to.path !== '/login' && !tokenStore.getToken) {
        next({
            path: '/login'
        })
    } else {
        if (!whiteRoute.includes(to.path)) {
            if (permissionStore.getMenu.length === 0) {
                permissionStore
                    .initMenu()
                    .then(result => {
                        if (result.code === SUCCESS_CODE) {
                            if (result.data && result.data.length > 0) {
                                pushRoute(router, HOME_ROUTE_NAME, generateRoutes(permissionStore.getMenu))
                                router.replace(to.fullPath)
                            } else {
                                notice.warning('请联系管理员分配用户权限')
                                next('/login')
                            }
                        } else {
                            next('/login')
                        }
                    })
                    .catch(err => {
                        console.error(err)
                        notice.warning('获取用户权限失败，请联系管理员')
                        next('/login')
                    })
            } else {
                next()
            }
        } else {
            next()
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})

export function setupRouter(app) {
    app.use(router)
}
